#!/usr/bin/env node

const { spawn } = require('child_process');
const path = require('path');

// 启动脚本 - 根据参数启动不同的服务
const service = process.argv[2] || 'all';

console.log(`启动服务: ${service}`);

// 获取所有子项目
const fs = require('fs');
const packagesDir = path.join(__dirname, '../packages');
const packages = fs.readdirSync(packagesDir).filter(item => {
  const itemPath = path.join(packagesDir, item);
  return fs.statSync(itemPath).isDirectory() && fs.existsSync(path.join(itemPath, 'package.json'));
});

switch (service) {
  case 'all':
    startAll();
    break;
  default:
    startSpecific(service);
    break;
}

function startAll() {
  console.log('启动所有服务...');
  
  const processes = [];
  
  packages.forEach((pkg, index) => {
    const packagePath = path.join(packagesDir, pkg);
    const packageJson = JSON.parse(fs.readFileSync(path.join(packagePath, 'package.json'), 'utf8'));
    
    console.log(`启动 ${packageJson.name} (${pkg})...`);
    
    const process = spawn('pnpm', ['--filter', packageJson.name, 'start'], {
      cwd: path.join(__dirname, '..'),
      stdio: 'pipe',
      shell: true
    });
    
    process.stdout.on('data', (data) => {
      console.log(`[${packageJson.name}] ${data.toString().trim()}`);
    });
    
    process.stderr.on('data', (data) => {
      console.error(`[${packageJson.name}] ERROR: ${data.toString().trim()}`);
    });
    
    processes.push(process);
  });
  
  // 优雅关闭
  process.on('SIGINT', () => {
    console.log('\n正在关闭所有服务...');
    processes.forEach(proc => {
      proc.kill('SIGINT');
    });
    process.exit(0);
  });
}

function startSpecific(serviceName) {
  const package = packages.find(pkg => {
    const packagePath = path.join(packagesDir, pkg);
    const packageJson = JSON.parse(fs.readFileSync(path.join(packagePath, 'package.json'), 'utf8'));
    return packageJson.name === serviceName || pkg === serviceName;
  });
  
  if (!package) {
    console.error(`未找到服务: ${serviceName}`);
    console.log('可用的服务:');
    packages.forEach(pkg => {
      const packagePath = path.join(packagesDir, pkg);
      const packageJson = JSON.parse(fs.readFileSync(path.join(packagePath, 'package.json'), 'utf8'));
      console.log(`  - ${packageJson.name} (${pkg})`);
    });
    process.exit(1);
  }
  
  const packagePath = path.join(packagesDir, package);
  const packageJson = JSON.parse(fs.readFileSync(path.join(packagePath, 'package.json'), 'utf8'));
  
  console.log(`启动 ${packageJson.name}...`);
  
  const process = spawn('pnpm', ['--filter', packageJson.name, 'start'], {
    cwd: path.join(__dirname, '..'),
    stdio: 'inherit',
    shell: true
  });
  
  process.on('error', (err) => {
    console.error('服务启动失败:', err);
  });
}

